import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_study_dongtai.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/date_utils.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/10.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
///代码清单 5-27 TabBarView 中使用的标签页面
///lib/code/code5/example_504_CustomScrollView.dart
class StudyDongTaiItemPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _StudyDongTaiItemPageState();
  }
}

class _StudyDongTaiItemPageState extends State<StudyDongTaiItemPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  //标签页面保活 或者称保持状态
  @override
  bool get wantKeepAlive => true;

  List<StudyDongTaiBean> _list = [];
  List<StudyDongTaiBean> _allList = [];
  AnimationController _animationController;

  Animation<Offset> _animation;

  @override
  void initState() {
    super.initState();

    _animationController = new AnimationController(vsync: this,duration: Duration(milliseconds: 1200));

    _animation = new Tween(begin: Offset(0, -1), end: Offset(0, 0)).animate(
        CurvedAnimation(curve: Curves.fastOutSlowIn, parent: _animationController));

    getNewsList();
  }

  @override
  void dispose() {
    _timer.cancel();
    _animationController.dispose();
    super.dispose();

  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (_list == null || _list.length == 0) {
      return Container(
        child: NoDataWidget(
          clickCallBack: () {
            getNewsList();
          },
        ),
      );
    }
    //一个列表 切记不要再使用 Scaffold
    //否则会拦截事件 失去滑动联动效果
    return ListView.builder(
      //去除内边距
      padding: EdgeInsets.all(0),
      //列表子Item个数
      itemCount: _list.length,
      //每个子Item的布局构建
      itemBuilder: (BuildContext context, int index) {
        return SlideTransition(position: _animation, child: buildBodyWidget(index));
      },
    );
  }

  //每个子Item的布局构建
  Widget buildBodyWidget(int index) {
    StudyDongTaiBean newsBean = _list[index];

    //水波纹点击事件监听
    return InkWell(
      //手指点击抬起时的回调
      onTap: () {
        //showWebViewPage(context: context, pageUrl: newsBean.detailUrl);
      },
      child: Container(
        margin: EdgeInsets.only(top: 1),
        padding: EdgeInsets.all(10),
        color: Colors.white,
        //线性布局左右排列
        child: Row(
          //主轴方向开始对齐 在这里是左对齐
          mainAxisAlignment: MainAxisAlignment.start,
          //交叉轴上开始对齐 在这里是顶部对齐
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //左侧的图片
            buildLeftImage(newsBean),
            //右侧的文本区域
            buildRightTextArea(index, newsBean)
          ],
        ),
      ),
    );
  }

  ///左侧的图片区域
  Container buildLeftImage(StudyDongTaiBean newsBean) {
    int obtainScore = newsBean.obtainScore;
    Color color;
    IconData iconData;
    if (obtainScore <=90 && obtainScore > 80) {
      iconData = Icons.text_rotate_up_sharp;
      color = Colors.deepOrangeAccent;
    } else if (obtainScore <= 80 && obtainScore > 60) {
      iconData = Icons.text_rotate_up_sharp;
      color = Colors.orangeAccent;
    } else if (obtainScore <= 60) {
      iconData = Icons.text_rotation_angleup_sharp;
      color = Colors.green;
    } else {
      iconData = Icons.tag_faces_rounded;
      color = Colors.redAccent;
    }

    return Container(
      margin: EdgeInsets.only(right: 12),
      child: ClipOval(
        child: Icon(
          iconData,
          color: color,
        ),
      ),
    );
  }

  ///右侧的文本区域
  Expanded buildRightTextArea(int index, StudyDongTaiBean newsBean) {
    return Expanded(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Expanded(
            child: Text(
              buildTitleFunction(newsBean),
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              maxLines: 3,
              style: TextStyle(fontSize: 16),
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Text(
            "${TimelineUtil.formatByDateTime(ViDateUtils.getDateTime(newsBean.createTime), locale: "zh")}",
            softWrap: true,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.right,
            maxLines: 3,
            style: TextStyle(fontSize: 14, color: Colors.black38),
          )
        ],
      ),
    );
  }

  Future<bool> getNewsList() async {
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.STUDY_DONGTAI_URL,
    );
    if (responseInfo.success) {
      Map map = responseInfo.data;
      List list = map["list"];
      list.forEach((element) {
        StudyDongTaiBean newsBean = StudyDongTaiBean.fromJson(element);
        _allList.add(newsBean);
      });
    }

    if(_allList.length>0){
      initRequestData();
      startTimer();
    }

    return true;
  }

  Timer _timer;
  int _currentIndex = 0;
  void initRequestData(){
    _currentIndex = 1;
    _list.add(_allList[_currentIndex]);
    _animationController.reset();
    _animationController.forward();
    setState(() {

    });
  }
  void startTimer(){
    _timer = Timer.periodic(Duration(milliseconds: 6400), (timer) {

      _currentIndex++;
      if (_currentIndex >= _allList.length - 1) {
        _currentIndex = 0;
      }
      _list.insert(0,_allList[_currentIndex]);
      _animationController.reset();
      _animationController.forward();
      setState(() {

      });
    });
  }

  String buildTitleFunction(StudyDongTaiBean newsBean) {
    String name = "***";
    if (newsBean != null &&
        newsBean.realName != null &&
        newsBean.realName.length > 0) {
      name = "${newsBean.realName.substring(1)}***";
    }

    String categoryOne = newsBean.categoryOne;
    if (categoryOne != null && categoryOne == "QUICK_PRACTICE") {
      categoryOne = "快速练习";
    } else {
      categoryOne = "_list";
    }

    double obtainScore = newsBean.obtainScore / 10;
    String obtainStr = "获取满分";
    if (obtainScore == 100) {
      obtainStr = "获取满分";
    } else if (obtainScore < 100 && obtainScore >= 90) {
      obtainStr = "离满分很近了";
    } else if (obtainScore < 90 && obtainScore >= 60) {
      obtainStr = "正在持续努力中";
    } else {
      obtainStr = "失误 答错了！！！";
    }

    return "$name  $categoryOne  $obtainStr";
  }
}
